package com.cennavi.minemapdemo.activity.mixlayer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.bean.TracePoint;
import com.cennavi.minemapdemo.util.Config;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.camera.CameraUpdateFactory;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.AnimatedMarkerLayer;
import com.minedata.minemap.overlay.AnimatedMarkerOptions;
import com.minedata.minemap.overlay.NavigationLayer;
import com.minedata.minemap.overlay.NavigationOptions;
import com.minemap.geojson.Point;
import com.minemap.turf.TurfMeasurement;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import static com.minedata.minemap.overlay.NavigationOptions.NAVIGATION_CAP_ROUND;
import static com.minedata.minemap.overlay.NavigationOptions.NAVIGATION_JOIN_ROUND;

public class MixAnimatedMarkerActivity extends AppCompatActivity {
    private MapView mMapView;
    private static MineMap mMineMap;
    private NavigationLayer mNavigationLayer;
    private AnimatedMarkerLayer mAnimatedMarkerLayer;
    AnimatedMarkerOptions.AnimatedMarkerItem car;
    private Context mContext;
    private List<TracePoint> points = new ArrayList<>();
    private String bitmapName = "car";
    private int index = 1;
    private int speedLevel = 1;

    private Button btnSpeed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);
        setContentView(R.layout.activity_mix_animatedmarker);
        initView();
        initMap();
    }

    private void initView() {
        mMapView = findViewById(R.id.mapview);
        btnSpeed = findViewById(R.id.speed);
        btnSpeed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                speedLevel++;

                if (speedLevel > 2) {
                    speedLevel = 0;
                }

                switch (speedLevel) {
                    case 1:
                        btnSpeed.setText("中速");
                        break;
                    case 2:
                        btnSpeed.setText("高速");
                        break;
                    default:
                        btnSpeed.setText("低速");
                        break;
                }
            }
        });
    }

    private void initMap() {
        mMapView.setApiBaseUrl(Config.API_BASE_URL);
        mMapView.setApiUrl(Config.API_URL);
        mMapView.setSpriteImageUrl(Config.SPRITE_GLYPHS_URL);
        mMapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @SuppressLint("RtlHardcoded")
            @Override
            public void onMapReady(MineMap oMineMap) {
                mMineMap = oMineMap;
                mMineMap.getUiSettings().setRotateGesturesEnabled(true);// 是否可以旋转地图
                mMineMap.getUiSettings().setTiltGesturesEnabled(true);
                mMineMap.getUiSettings().setLogoEnabled(true);
                mMineMap.setRepaint(true);
                mMineMap.setStyleUrl(Config.BASE_URL + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {
                    @Override
                    public void onStyleLoaded(String s) {
                        mMineMap.setTrafficShow(true); //是否展示交通路况信息
                        mMineMap.setTrafficRote(60);//路况刷新时间
                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ic_car_top_small);
                        mMineMap.addImage(bitmapName, bitmap);
                        getTraceData();
                        addRoute();
                    }
                });
                //设置指南针是否显示，默认是显示
                mMineMap.getUiSettings().setCompassEnabled(true);
                mMineMap.setCameraPosition(
                        new CameraPosition.Builder().target(new LatLng(26.250457, 107.563054))
                                .zoom(11)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                mMineMap.setMaxZoomPreference(17);//设置最高展示级别，最高为17级别
                mMineMap.setMinZoomPreference(3);//设置最低的展示级别
            }
        });
    }

    public void addCar(View view) {
        mMineMap.animateCamera(CameraUpdateFactory.newLatLngZoom(points.get(0).getLatLng(), 13), 1000);
        AnimatedMarkerOptions options = new AnimatedMarkerOptions("animatedmarkerlayer");
        mAnimatedMarkerLayer = mMineMap.addLayer(options);
        LatLng start = points.get(0).getLatLng();
        LatLng end = points.get(1).getLatLng();

        long during = (points.get(1).getTimestamp() - points.get(0).getTimestamp()) * 100;

        switch (speedLevel) {
            case 1:
                during = (long) (during * 1.5);
                break;
            case 2:
                during = (long) (during * 2);
                break;
            default:
                break;
        }

        car = new AnimatedMarkerOptions.AnimatedMarkerItem(start, end)
                .icon(bitmapName).iconRotate(getBearing(start, end)).setDuration(during);
        mAnimatedMarkerLayer.set(car);
        mAnimatedMarkerLayer.update();
        mAnimatedMarkerLayer.startAnimators();
        mAnimatedMarkerLayer.setOnAnimationEndListener(new AnimatedMarkerLayer.OnAnimationEndListener() {
            @Override
            public void onAnimationEnd() {
                if (index < points.size() - 1) {
                    updateCar();
                }
            }
        });
    }

    public void updateCar() {
        LatLng start = points.get(index).getLatLng();
        LatLng end = points.get(index + 1).getLatLng();
        long during = (points.get(index + 1).getTimestamp() - points.get(index).getTimestamp()) * 100;

        switch (speedLevel) {
            case 1:
                during = (long) (during / 4);
                break;
            case 2:
                during = during / 8;
                break;
            default:
                break;
        }

        car.trackStartPoint(start).trackEndPoint(end)
                .iconRotate(getBearing(start, end)).setDuration(during);

        mAnimatedMarkerLayer.set(car);
        mAnimatedMarkerLayer.update();
        mAnimatedMarkerLayer.startAnimators();
        index++;
    }

    //添加路线
    public void addRoute() {
        if (mNavigationLayer != null) {
            mMineMap.removeLayer(mNavigationLayer);
            mNavigationLayer = null;
        }

        if (mAnimatedMarkerLayer != null) {
            mMineMap.removeLayer(mAnimatedMarkerLayer);
            mNavigationLayer = null;
        }

        NavigationOptions options = new NavigationOptions("navigationlayer");
        options.setAlpha(1.0f);
        options.setWidth(8.0f);
        options.setAnimationDuration(1000);
        options.setAnimationMode(NavigationOptions.NAVIGATION_ANIMATION_MODE_SINGLE);
        options.setCapType(NAVIGATION_CAP_ROUND);
        options.setJoinType(NAVIGATION_JOIN_ROUND);
        options.setBottomColorEnabled(true);
        options.setBottomColor("#C0C0C0");
        options.setProgressMode(NavigationOptions.NAVIGATION_PROGRESS_MODE_LTE);
        options.setProgress(0);
        options.addAll(getTracePointsData());
        mNavigationLayer = mMineMap.addLayer(options);
    }

    //获取轨迹数据
    public void getTraceData() {
        try {
            InputStream instream = getAssets().open("trace_data.csv");


            if (instream != null) {
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;

                while ((line = buffreader.readLine()) != null) {
                    String everyLine = line;
                    String[] strarray = everyLine.split(",");

                    double longitude = Double.parseDouble(strarray[0]);
                    double latitude = Double.parseDouble(strarray[1]);
                    long ts = Long.parseLong(strarray[2]);
                    TracePoint point = new TracePoint(new LatLng(latitude, longitude), ts);
                    points.add(point);

                    if (points.size() > 99) {
                        break;
                    }
                }
                instream.close();
                buffreader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取路线数据
    public List<NavigationOptions.NavigationItem> getTracePointsData() {
        List<NavigationOptions.NavigationItem> items = new ArrayList<>();
        List<LatLng> latLngs = new ArrayList<>();

        for (TracePoint point : points) {
            latLngs.add(point.getLatLng());
        }

        NavigationOptions.NavigationItem item = new NavigationOptions.NavigationItem(latLngs, "#3CB371");
        items.add(item);
        return items;
    }

    private static float getBearing(LatLng from, LatLng to) {
        return (float) TurfMeasurement.bearing(
                Point.fromLngLat(from.getLongitude(), from.getLatitude()),
                Point.fromLngLat(to.getLongitude(), to.getLatitude())
        );
    }

    @Override
    protected void onStart() {
        if (mMapView != null) {
            mMapView.onStart();
        }
        super.onStart();
    }

    @Override
    protected void onResume() {
        if (mMapView != null)
            mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mMapView != null)
            mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mMapView != null)
            mMapView.onStop();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (mAnimatedMarkerLayer != null) {
            mAnimatedMarkerLayer.cancelAnimators();
        }

        if (mMapView != null)
            mMapView.onDestroy();
        super.onDestroy();
    }

}
